import {
  Injectable,
  PipeTransform,
  ArgumentMetadata,
  Type,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import { plainToClass } from 'class-transformer';
import { validate } from 'class-validator';

@Injectable()
export class ValidationPipe implements PipeTransform<any> {
  constructor() {}

  toValidate(metatype: Type<any>): boolean {
    const types = [String, Boolean, Number, Array, Object];
    return !types.find((type) => metatype === type);
  }

  async transform(value: any, metadata: ArgumentMetadata) {
    console.log(value);
    let { metatype } = metadata;
    if (!metatype || !this.toValidate(metatype)) {
      return value;
    }

    let object = plainToClass(metatype, value);
    let errors = await validate(object);

    if (errors.length > 0) {
      let errObj = {};
      errors.forEach((err) => {
        const { property, constraints } = err;
        errObj[property] = Object.values(constraints);
      });
      throw new HttpException(
        {
          message: 'Request params validation failed',
          error: errObj,
        },
        HttpStatus.BAD_REQUEST,
      );
    }

    return value;
  }
}
